package com.shop.cereshop.app.tencent.im.service.impl;

import com.shop.cereshop.app.tencent.im.model.coupon.ReceiveCouponParam;
import com.shop.cereshop.app.tencent.im.service.CouponMsgService;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.constant.IntegerEnum;
import com.shop.cereshop.commons.result.Result;
import com.shop.cereshop.app.param.coupon.CouponParam;
import com.shop.cereshop.app.service.activity.CereBuyerCouponService;
import com.shop.cereshop.commons.domain.buyer.CereBuyerUser;
import com.shop.cereshop.commons.exception.CoBusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @description: 优惠券消息服务实现
 * @author zdd
 * @date 2025/11/10
 * @version 1.0
 */
@Slf4j
@Service
public class CouponMsgServiceImpl implements CouponMsgService {

  @Resource
  private CereBuyerCouponService cereBuyerCouponService;

  @Override
  public Result<Void> receiveCoupon(Long buyerUserId, ReceiveCouponParam param) {
    // 1. 参数校验
    if (param == null || param.getCouponId() == null) {
      return Result.custom(CoReturnFormat.FAIL, "优惠券ID不能为空");
    }

    try {
      // 2. 构建优惠券参数
      CouponParam couponParam = new CouponParam();
      couponParam.setCouponId(param.getCouponId());
      couponParam.setSource(IntegerEnum.COUPON_SOURCE_TAKE.getCode());

      // 3. 构建用户对象
      CereBuyerUser user = new CereBuyerUser();
      user.setBuyerUserId(buyerUserId);

      // 4. 调用现有的领取逻辑，复用现有逻辑
      cereBuyerCouponService.takeCoupon(couponParam, user);

      log.info("用户[{}]成功领取IM优惠券[{}]", buyerUserId, param.getCouponId());
      return Result.success();
    } catch (CoBusinessException e) {
      log.warn("用户[{}]领取IM优惠券[{}]异常: {}", buyerUserId, param.getCouponId(), e.getMessage());
      return Result.custom(e.getCode(), e.getMessage());
    } catch (Exception e) {
      log.error("用户[{}]领取IM优惠券[{}]异常", buyerUserId, param.getCouponId(), e);
      return Result.custom(CoReturnFormat.FAIL, "领取优惠券失败，请稍后重试");
    }
  }

}
